package com.bootdo.quota.util;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.ExceptionUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.quota.dao.QuotaDao;
import com.bootdo.quota.domain.QuotaDO;
import com.bootdo.quota.domain.QuotaHistoryDO;
import com.bootdo.quota.dao.QuotaHistoryDao;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @Desc 额度调整MQ工具类
 * @date 2020/3/20
 *
 */
@Component
public class QuotaUtil {

    private static final Logger logger = LoggerFactory.getLogger(QuotaUtil.class);

    @Autowired
    private QuotaDao quotaMapper;
    @Autowired
    private QuotaHistoryDao quotaHistoryMapper;

    @RabbitListener(queues = "topic.payee.quota")
    public void updateQuota(Channel channel, Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(msg);
            logger.debug("接收到用户，用户ID：【" + jsonObject.getString("userId") + "】额度变更信息，>>>>>>>>>>>>>>>>>>>>>>>>>接收到数据" + msg);
            Long userId = jsonObject.getLong("userId");
            double money = jsonObject.getDouble("money");
            String reason = jsonObject.getString("reason");
            String orderId = jsonObject.getString("orderId");
            int changeType = jsonObject.getInteger("type");
            QuotaDO quota = quotaMapper.get(userId);
            double available = quota.getActualQuota();
            //新的业务规则相当于修改主表额度
            Long id = quota.getId();
            quota = new QuotaDO();
            quota.setId(id);
            if (StringUtils.isBlank(orderId)){
                quota.setActualQuota(money);
            } else {
                quota.setActualQuota(changeType == 1 ? available + money : available - money);
            }
            quotaMapper.updateByInfo(quota);

            //就相当于往额度流水表增加记录
            QuotaHistoryDO historyDO = new QuotaHistoryDO();
            if (StringUtils.isNotBlank(orderId) && !"TC0001".equals(orderId)){
                historyDO.setOrderNo(orderId);
            }
            historyDO.setUserId(userId);
            historyDO.setQuota(available);
            if (StringUtils.isBlank(orderId)){
                historyDO.setActualQuota(money);
            } else {
                historyDO.setActualQuota(changeType == 1 ? available + money : available - money);
            }
            historyDO.setChangeReason(reason);
            historyDO.setStatus(2);
            historyDO.setChangeType(changeType);
            historyDO.setGmtDate(new Date());
            quotaHistoryMapper.saveBySelectMaxVersion(historyDO);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.debug("消息topic.payee.quota消费成功：id：{}", message.getMessageProperties().getDeliveryTag());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("=====修改流水异常=====>" + ExceptionUtils.getStackTraceAsString(e));
            //丢弃这条消息
            try {
                //最后一个参数是：是否重回队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
            } catch (IOException e1) {
                logger.error("业务处理异常："+e1.getMessage());
                logger.error("消息消费失败：id：{}",message.getMessageProperties().getDeliveryTag());
                e1.printStackTrace();
            }
        }
    }
}
